package Services

import (
	"errors"
	"gorm.io/gorm"
	"minititok/Entities"
	"minititok/databases"
)

func Ensurefavorites(username string, Av string) (*Entities.Favorite, error) {
	var fav Entities.Favorite
	DBerr := databases.DB.Where("username = ? AND av = ?", username, Av).First(&fav).Error
	if errors.Is(DBerr, gorm.ErrRecordNotFound) {
		newFav := Entities.Favorite{
			Username:  username,
			Av:        Av,
			Favorited: false,
		}
		if err := databases.DB.Create(&newFav).Error; err != nil {
			return nil, err
		}
		return &newFav, nil
	} else if DBerr != nil {
		return nil, DBerr
	}
	return &fav, nil
}

func FindFavoritesByAvAndUsername(av string, username string) (*Entities.Favorite, error) {
	var fav Entities.Favorite
	err := databases.DB.Where("av = ? AND username = ?", av, username).First(&fav).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return nil, nil
	}
	return &fav, nil
}

func UpdateFavorite(fav *Entities.Favorite, isFavorited bool) error {
	fav.Favorited = isFavorited
	res := databases.DB.Model(fav).
		//Select("favorited").
		//Where("av = ? AND username = ?", fav.Av, fav.Username).
		Update("favorited", fav.Favorited)

	if res.Error != nil {
		return res.Error
	}
	return nil
}
